package com.kosmos.dubhe.wxcp.controller;

import cn.hutool.core.codec.Base64;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.kosmos.dubhe.wxcp.provider.MessageType;
import com.kosmos.dubhe.wxcp.provider.WxCpMessageSender;
import com.kosmos.dubhe.wxcp.setting.WxcpSenderSetting;
import com.kosmos.dubhe.wxcp.utils.Sm2Encryption;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.util.Strings;
import org.bouncycastle.util.Arrays;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * @author wukai
 */
@JsonFormat
@RestController
@RequestMapping(value = "/wxcp")
@RequiredArgsConstructor
@Slf4j
public class CommonMessageController {
    private final WxCpMessageSender sender;
    private final WxcpSenderSetting setting;
    private final static Duration MIN_INTERVAL_SECOND = Duration.ofMinutes(5);
    private final static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @SneakyThrows
    @RequestMapping(value = "/sendDefaultChannel", method = RequestMethod.GET)
    public String sendDefaultChannel(
            @RequestParam(value = "tagName", required = false, defaultValue = "") String tagName,
            @RequestParam(value = "tagId", required = false, defaultValue = "") String tagId,
            @RequestParam(value = "departmentName", required = false, defaultValue = "") String departmentName,
            @RequestParam(value = "departmentId", required = false, defaultValue = "") String departmentId,
            @RequestParam(value = "userCode", required = false, defaultValue = "") String userCode,
            @RequestParam(value = "userName", required = false, defaultValue = "") String userName,
            @RequestParam(value = "messageType", required = false, defaultValue = "TEXT") String messageType,
            @RequestParam(value = "sendName") String sendName,
            @RequestParam(value = "sendDateTime") String sendDateTime,
            //  @RequestParam(value = "party", required = false, defaultValue = "") String party,
            @RequestParam(value = "content") String content) {
        String c = Sm2Encryption.decryptFromBase64(content, setting.getPrivateKey());
        /*if (!StringUtils.isEmpty(party)) {
            message = WxCpMessage.TEXT().toParty(party).content(content).build();
        } else */
        String sn = Base64.decodeStr(sendName.replace(' ', '+'));
        LocalDateTime sendTime = LocalDateTime.parse(Base64.decodeStr(sendDateTime.replace(' ', '+')), FORMATTER);
        LocalDateTime currentTime = LocalDateTime.now();
        log.debug("CommonMessageController sendDefaultChannel sendTime:{} ", sendTime);
        boolean expired = Duration.between(sendTime, currentTime).compareTo(MIN_INTERVAL_SECOND) > 0;
        if (expired) {
            return "消息已过期, 请重新发送";
        }
        String cs = c + "\r\n\r\n\r\n\r\n                (此消息由" + sn + "发送)";
        if (!Strings.isEmpty(tagId)) {
            String t = Base64.decodeStr(tagId.replace(' ', '+'));
            sender.broadcastMessageDefaultChannel(MessageType.valueOf(messageType.toUpperCase()), t, cs);
        } else if (!Strings.isEmpty(tagName)) {
            String t = Base64.decodeStr(tagId.replace(' ', '+'));
            sender.broadcastMessageToTagNameDefaultChannel(MessageType.valueOf(messageType.toUpperCase()), t, cs);
        } else if (!Strings.isEmpty(departmentId)) {
            Long d = Long.valueOf(Base64.decodeStr(departmentId.replace(' ', '+')));
            sender.broadcastPartyMessageDefaultChannel(MessageType.valueOf(messageType.toUpperCase()), d, cs);
        } else if (!Strings.isEmpty(departmentName)) {
            String d = Base64.decodeStr(departmentName.replace(' ', '+'));
            sender.broadcastPartyMessageDefaultChannel(MessageType.valueOf(messageType.toUpperCase()), d, cs);
        } else if (!Strings.isEmpty(userCode)) {
            String u = Base64.decodeStr(userCode.replace(' ', '+'));
            sender.notifyMessageDefaultChannel(MessageType.valueOf(messageType.toUpperCase()), u, cs);
        } else if (!Strings.isEmpty(userName)) {
            String n = Base64.decodeStr(userName.replace(' ', '+'));
            String[] multiUserName = n.contains(",") ? n.split(",", -2) : null;
            if (!Arrays.isNullOrEmpty(multiUserName)) {
                sender.broadcastMultiUserNameMessageDefaultChannel(MessageType.valueOf(messageType.toUpperCase()), multiUserName, cs);
            } else {
                sender.alertMessageDefaultChannel(MessageType.valueOf(messageType.toUpperCase()), n, cs);
            }
        } else {
            return "one of userCode or tagId or userName must be not empty";
        }
        return "发送成功";
    }

    @SneakyThrows
    @RequestMapping(value = "/send/{agentId}", method = RequestMethod.GET)
    public String send(
            @PathVariable(value = "agentId") Integer agentId,
            @RequestParam(value = "userCode", required = false, defaultValue = "") String userCode,
            @RequestParam(value = "userName", required = false, defaultValue = "") String userName,
            @RequestParam(value = "tagId", required = false, defaultValue = "") String tagId,
            @RequestParam(value = "messageType", required = false, defaultValue = "TEXT") String messageType,
            //  @RequestParam(value = "party", required = false, defaultValue = "") String party,
            @RequestParam(value = "content") String content) {
        String c = Sm2Encryption.decryptFromBase64(content, setting.getPrivateKey());
        /*if (!StringUtils.isEmpty(party)) {
            message = WxCpMessage.TEXT().toParty(party).content(content).build();
        } else */
        if (!Strings.isEmpty(tagId)) {
            String t = Base64.decodeStr(tagId.replace(' ', '+'));
            sender.broadcastMessage(agentId, MessageType.valueOf(messageType.toUpperCase()), t, c);
        } else if (!Strings.isEmpty(userCode)) {
            String u = Base64.decodeStr(userCode.replace(' ', '+'));
            sender.notifyMessage(agentId, MessageType.valueOf(messageType.toUpperCase()), u, c);
        } else if (!Strings.isEmpty(userName)) {
            String n = Base64.decodeStr(userName.replace(' ', '+'));
            sender.alertMessage(agentId, MessageType.valueOf(messageType.toUpperCase()), n, c);
        } else {//1000002
            return "one of userCode or tagId or userName must be not empty";
        }
        return "发送成功";
    }


}
